package com.itheima.d7_sync.no3;

import java.util.concurrent.locks.Lock;

public class MyRunnable implements Runnable {
    //持有的账号
    Account account;
    //要取出的钱
    int money;
    //锁对象
    Lock lock;

    public MyRunnable(Account account, int money,Lock lock) {
        this.account = account;
        this.money = money;
        this.lock = lock;
    }

    @Override
    public void run() {
        //1.找到操作共享资源，并容易出现线程安全问题的代码

        //2.使用Lock对象，调用lock()方法上锁
        lock.lock();
        if (money <= account.getBalance()) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            account.setBalance(account.getBalance() - money);
            System.out.println(Thread.currentThread().getName() + "取出" + money);
        } else {
            System.out.println(Thread.currentThread().getName() + "取钱时，余额不足");
        }

        //3.共享资源的代码执行完，还需要调用Lock的unlock()方法解锁
        lock.unlock();

        System.out.println("剩余：" + account.getBalance());
    }
}
